package middleware

import (
	"demo/web/gin/router/params"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
	"time"
)

//统计耗时中间件
func StatCost() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		if strings.Contains(path, "/static") || strings.HasSuffix(path, ".ico") {
			c.Next()
			return
		}

		start := time.Now()
		//执行后面的handler
		if strings.HasSuffix(c.Request.URL.Path, "haha1") {
			c.AbortWithStatusJSON(200, gin.H{
				"message": "haha1 abort with json",
			})
		} else if strings.HasSuffix(c.Request.URL.Path, "haha2") {
			//http response状态码返回200，body为空，content-length=0
			c.AbortWithStatus(200)
		} else if strings.HasSuffix(c.Request.URL.Path, "haha3") {
			//http response状态码返回200，body为空，content-length=0
			//content记录error
			c.AbortWithError(200, errors.New("haha3 aborted"))
		} else if strings.HasSuffix(c.Request.URL.Path, "haha4") {
			//返回 status code 404,  body为404 not found
			c.Abort()
		} else {
			//进入下一个handler, handler执行完后退到当前位置
			c.Next()
		}

		cost := time.Since(start).Milliseconds()
		fmt.Println("cost=" + strconv.FormatInt(int64(cost), 10) + "ms")
	}
}

func LoginFilter() gin.HandlerFunc {
	return func(c *gin.Context) {
		//检查登录状态，从cookie或请求参数中获取登录token，并在服务端校验
		userInfo := params.CheckLogin(c)
		if userInfo == nil {
			c.AbortWithStatusJSON(403, gin.H{
				"message": "not login",
			})
			return
		} else {
			c.Next()
		}
	}
}
